import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/bean/calendar_attendance_status_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../../app_main.dart';

/// 企业详情搜索页
///
/// @author: zengxiangxi
/// @createTime: 3/22/21 6:39 PM
/// @specialDemand:
class CorrectionSearchPage extends StatefulWidget {
  final FaceuserBean faceuserBean;
  ///路由名称
  static const String ROUTER = "CompanyDetailSearchPage";

  const CorrectionSearchPage({Key key, this.faceuserBean}) : super(key: key);

  @override
  _CorrectionSearchPageState createState() =>
      _CorrectionSearchPageState();

  ///跳转方法
  static Future<CompanyDetailByTypeListItemBean> navigatorPush(BuildContext context,FaceuserBean faceuserBean) {
    return RouterUtils.routeForFutureResult(
      context,
      CorrectionSearchPage(
          faceuserBean:faceuserBean
      ),
      routeName: CorrectionSearchPage.ROUTER,
    );
  }
}

class _CorrectionSearchPageState extends BaseState<CorrectionSearchPage> {
  ValueNotifier<String> searchPageValueNotifier;


  CommonListPageWidgetState mState;
  @override
  void initState() {
    super.initState();
    searchPageValueNotifier = ValueNotifier(null);
  }

  @override
  void dispose() {
    searchPageValueNotifier.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Color(0xFF22263a),
      backgroundColor:ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: Column(
        children: <Widget>[
          SizedBox(
            height: ScreenUtils.getStatusBarH(context),
          ),
          _toSearchBarWidget(),
          _toListItemWidget()
        ],
      ),
    );
  }

  Widget _toSearchBarWidget() {
    return Container(
      height: 44,
      child: Row(
        children: <Widget>[
          Expanded(
            child: CommonSearchBarWidget(
                hintText: "输入姓名",
                autoFocus: true,
                margin: const EdgeInsets.only(left: 15),
                onChanged: (String searchStr) {
                  searchPageValueNotifier.value = searchStr?.trim();
                  mState?.viewModel?.refresh();
                  setState(() {

                  });
                },
                onSubmitted: (String searchStr) {
                  searchPageValueNotifier.value = searchStr?.trim();
                  setState(() {

                  });
                }),
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              RouterUtils.pop(context);
            },
            child: Container(
              width: 60,
              height: 30,
              child: Center(
                child: Text(
                  "取消",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Color(0xFFD0E0F7), fontSize: 15, height: 1.2),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }


Widget _toListItemWidget() {
  return Expanded(
    child: CommonListPageWidget<CompanyDetailByTypeListItemBean, CompanyDetailByTypeListResponseBean>(
      enablePullUp: false,
      enablePullDown: true,
      queryMapFunc: (int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "current": page ?? 1,
        "size": 1000,
        "groupid": "",
        "groupType": "",
        "searchName": searchPageValueNotifier?.value == null || searchPageValueNotifier?.value == "" ?"%-&-@-%" :searchPageValueNotifier?.value,
        // "searchOthers": searchPageValueNotifier?? "",
      },
      parseDataFunc: (VgHttpResponse resp) {
        CompanyDetailByTypeListResponseBean vo =
        CompanyDetailByTypeListResponseBean.fromMap(resp?.data);
        return vo;
      },
      listFunc: (List<CompanyDetailByTypeListItemBean> companySearchItemList) {

      },
      stateFunc: (CommonListPageWidgetState state) {
        mState = state;
      },
      itemBuilder: (BuildContext context, int index,
          CompanyDetailByTypeListItemBean itemBean) {
        if (itemBean == null) return Container();
        return _searchDetailListItemWidget(itemBean,);
        // return CompanySearchDetailListItemWidget(itemBean: itemBean,);
      },
      //分割器构造器
      separatorBuilder: (context, int index, _) {
        return Container(
          height: 0.5,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          padding: const EdgeInsets.only(left: 15),
          child: Container(
            color: Color(0xFF303546),
          ),
        );
        // return divider;
      },
      placeHolderFunc: (List<CompanyDetailByTypeListItemBean> list, Widget child,
          VoidCallback onRefresh) {
        return VgPlaceHolderStatusWidget(
          emptyStatus: list == null || list.isEmpty,
          emptyOnClick: () => onRefresh(),
          child: child,
        );
      },
      netUrl:ServerApi.BASE_URL + "app/appCompanyPages",
      httpType: VgHttpType.get,
    ),
  );
}

 Widget _searchDetailListItemWidget(CompanyDetailByTypeListItemBean itemBean){
   return GestureDetector(
     behavior: HitTestBehavior.translucent,
     onTap: (){
       RouterUtils.pop(context, result: itemBean);
     },
     child: Container(
         height: 64,
         margin: const EdgeInsets.symmetric(horizontal: 15),
     child: _toMainRowWidget(context,itemBean)
     ),
   );
}
  Widget _toMainRowWidget(BuildContext context,CompanyDetailByTypeListItemBean itemBean) {
    return Row(
      children: <Widget>[
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Container(
            width: 36,
            height: 36,
            child: VgCacheNetWorkImage(
              showOriginEmptyStr(itemBean?.putpicurl) ??
                  showOriginEmptyStr(itemBean?.napicurl ?? "") ??
                  (itemBean?.pictureUrl ?? ""),
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
              defaultErrorType: ImageErrorType.head,
              defaultPlaceType: ImagePlaceType.head,
            ),
          ),
        ),
        SizedBox(
          width: 10,
        ),
        Container(
          height: 36,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: (VgStringUtils.checkAllEmpty([
              itemBean?.department?.trim(),
              itemBean?.projectname?.trim(),
              itemBean?.city?.trim(),
              itemBean?.classname?.trim(),
              // itemBean?.coursename?.trim(),
            ]))
                ? MainAxisAlignment.center
                : MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  (itemBean?.isUnknow() ?? false)
                      ? Text(
                    "未知",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getMinorRedColor_F95355(),
                        fontSize: 15,
                        height: 1.2),
                  )
                      : CommonNameAndNickWidget(
                    name: itemBean?.name,
                    nick: itemBean?.nick,
                  ),
                  VgLabelUtils.getRoleLabel(itemBean?.roleid) ?? Container(),
                  _toPhoneWidget(itemBean),
                ],
              ),
              if (!VgStringUtils.checkAllEmpty([
                itemBean?.department?.trim(),
                itemBean?.projectname?.trim(),
                itemBean?.city?.trim(),
                itemBean?.classname?.trim(),
                // itemBean?.coursename?.trim(),
              ]))
                Builder(builder: (BuildContext context) {
                  return CommonConstraintMaxWidthWidget(
                    maxWidth: ScreenUtils.screenW(context)/2,
                    child: Text(
                      // (itemBean?.isUnknow() ?? false)
                      //     ? (VgDateTimeUtils.getFormatTimeStr(
                      //             itemBean?.lastPunchTime) ??
                      //         "")
                      //     : (StringUtils.isNotEmpty(itemBean?.phone)
                      //         ? "${itemBean.phone}"
                      //         : "暂无手机号码"),
                      VgStringUtils.getSplitStr([
                        itemBean?.department?.trim(),
                        //项目和城市暂时不展示
                        // itemBean?.projectname?.trim(),
                        // itemBean?.city?.trim(),
                        itemBean?.classname?.trim(),
                        // itemBean?.coursename?.trim(),
                      ], symbol: "/"),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 12,
                      ),
                    ),
                  );
                }),
            ],
          ),
        ),
        Expanded(
          child: _toColumnWidget(itemBean),
        ),
        if (itemBean?.isUnknow() ?? false)
          Container(
            width: 60,
            height: 28,
            margin: const EdgeInsets.only(left: 15),
            decoration: BoxDecoration(
              border: Border.all(color: VgColors.INPUT_BG_COLOR, width: 0.5),
              borderRadius: BorderRadius.circular(14),
            ),
            child: Center(
              child: Text(
                "标记",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 13,
                ),
              ),
            ),
          ),
      ],
    );
  }

  Widget _toColumnWidget(CompanyDetailByTypeListItemBean itemBean) {
    return DefaultTextStyle(
      style: TextStyle(height: 1.2),
      child: Container(
        height: 36,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              height: 21,
              alignment: Alignment.centerLeft,
              child: Row(
                children: <Widget>[
                  Spacer(),
                  Text.rich(TextSpan(children: [
                    TextSpan(
                      text: "${_getAddOrMarkUserAndStatusStr(itemBean) ?? ""}",
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 10,
                      ),
                    ),
                    TextSpan(
                      text: ((itemBean?.isAlive() ?? true) || !UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition()) ? "" : "·",
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 10,
                      ),
                    ),
                    if (!(itemBean?.isUnknow() ?? false) && UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition())
                      TextSpan(
                        text: (itemBean?.isAlive() ?? true) ? "" : "未激活",
                        style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getMinorRedColor_F95355(),
                          fontSize: 10,
                        ),
                      ),
                  ]))
                ],
              ),
            ),
            // if (!VgStringUtils.checkAllEmpty([
            //   itemBean?.department?.trim(),
            //   itemBean?.projectname?.trim(),
            //   itemBean?.city?.trim(),
            // ]))
            Row(
              children: <Widget>[
                Spacer(),
                Text(
                  _getGroupAndIdStr(itemBean?.groupName, itemBean?.number) ??
                      "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 12,
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  String _getGroupAndIdStr(String groupName, String number) {
    if (StringUtils.isEmpty(groupName) && StringUtils.isEmpty(number)) {
      return null;
    }
    if (StringUtils.isNotEmpty(groupName) && StringUtils.isEmpty(number)) {
      return groupName;
    }
    if (StringUtils.isEmpty(groupName) && StringUtils.isNotEmpty(number)) {
      return number;
    }
    return groupName + "·" + number;
  }

  String _getAddOrMarkUserAndStatusStr(CompanyDetailByTypeListItemBean itemBean) {
    if ((itemBean?.isAlive() ?? false) && itemBean.lastPunchTime != null) {
      return VgDateTimeUtils.getFormatTimeStr(itemBean.lastPunchTime) + "刷脸";
    }
    if (StringUtils.isEmpty(itemBean?.uname)) {
      return null;
    }
    StringBuffer stringBuffer = StringBuffer(itemBean?.uname);

    /// tpe  00标记录入 01app手动添加
    if (!(itemBean?.isMark() ?? false)) {
      stringBuffer.write("添加");
    } else {
      stringBuffer.write("标记");
    }
    return stringBuffer.toString();
  }

  Widget _toPhoneWidget(CompanyDetailByTypeListItemBean itemBean) {
    return Offstage(
      offstage: itemBean.phone == null || itemBean.phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(itemBean?.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }
}
